package com.egg.basic.config.aliyun;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.egg.basic.util.EmailUtil;
import com.egg.basic.util.FileAliyunUtil;
import com.egg.common.spring.util.SpringContextUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * 阿里配置
 */
@Profile({"prod", "test", "dev"})
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "file.aliyun")
public class AliyunOSSConfig {


    // endpoint是阿里云OSS服务的endpoint，可以在控制台中找到
    private String endpoint;
    // accessKeyId和accessKeySecret分别是阿里云OSS服务的AK和SK，可以在控制台中找到
    private String accessKeyId;
    private String accessKeySecret;
    // 桶名称
    private String bucketName;


    @Bean
    public OSS getOSSClient() {
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSupportCname(true);
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
    }

    /**
     * 装配
     *
     * @return
     */
    @Bean
    FileAliyunUtil initFileAliyunUtil(OSS oss) {
        FileAliyunUtil fileAliyunUtil = new FileAliyunUtil();
        if (null == oss) {
            log.error("初始化失败 {} 原因 {}", EmailUtil.class.getName(), FileAliyunUtil.class.getName() + "为null");
            return fileAliyunUtil;
        }
        fileAliyunUtil.setOSS(oss);
        //  判断容器是否存在,不存在就创建
        if (!oss.doesBucketExist(bucketName)) {
            oss.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            oss.createBucket(createBucketRequest);
            // 设置权限(公开读)
            oss.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }
        log.info("初始化成功 {}", FileAliyunUtil.class.getName());
        return fileAliyunUtil;
    }

    public static String bucketName() {
        AliyunOSSConfig bean = SpringContextUtil.getBean(AliyunOSSConfig.class);
        return bean.getBucketName();
    }

}